/**
 * Todo的视图
 */

import { Stream } from 'xstream';
import { VNode } from '@cycle/dom';
import { TodoState } from '../../types';
import * as classNames from 'classnames';

/**
 * List的视图
 * @param state$ 
 */
export default function view(state$ : Stream<TodoState>) : Stream<VNode> {
    return state$
            .map(({title, completed, editing}) => {
                // hook-update
                const focus = (oldNode: VNode, { elm }: VNode) => {
                    const input = elm as HTMLInputElement;
                    input.value = title;
                    if (editing) {
                        input.focus();
                        input.selectionStart = input.value.length;
                    }
                }

                return <li className={classNames({todoRoot: true,completed, editing})}> 
                    <div className='view'>
                        <input 
                            type='checkbox' 
                            className='toggle' 
                            checked={completed}
                        />
                        <label>{title}</label>
                        <button className='destroy'></button>
                    </div>
                    <input 
                        type='text' 
                        className='edit' 
                        hook-update={focus}
                    />
                </li>
            });
}